import styles from './index.module.scss'
import ArticleItem from '../ArticleItem'
import { useDispatch, useSelector } from 'react-redux'
import { useEffect, useState } from 'react'
import { getArticleList } from '@/store/actions/home'
import { PullToRefresh, InfiniteScroll } from 'antd-mobile'
/**
 * 文章列表组件
 * @param {String} props.channelId 当前文章列表所对应的频道ID
 * @param {String} props.aid 当前 Tab 栏选中的频道ID
 */
const ArticleList = ({ channelId, aid }) => {
  const dispatch = useDispatch()
  const currentObj = useSelector((state) => state.home.articles[channelId])
  const list = currentObj?.list || []
  const [hasMore, setHasMore] = useState(true)
  const [isLoading, setIsloading] = useState(false)
  const timestamp = currentObj?.timestamp
  useEffect(() => {
    if (currentObj) return
    if (channelId === aid) {
      dispatch(getArticleList(channelId, +new Date()))
    }
  }, [dispatch, channelId, aid, currentObj])

  const onRefresh = async () => {
    await dispatch(getArticleList(channelId, +new Date()))
  }
  const loadMore = async () => {
    if (timestamp === null) {
      setHasMore(false)
      return
    }
    if (!isLoading) {
      setIsloading(true)
      await dispatch(getArticleList(channelId, timestamp, true))
      setIsloading(false)
    }
  }
  if (currentObj) {
    return (
      <div className={styles.root}>
        <div className="articles">
          <PullToRefresh onRefresh={onRefresh}>
            {list.map((item) => (
              <div className="article-item" key={item.art_id}>
                <ArticleItem article={item}></ArticleItem>
              </div>
            ))}
          </PullToRefresh>
          <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
        </div>
      </div>
    )
  } else {
    return null
  }
}

export default ArticleList
